<template>
  <view class="question-card">
    <!-- 题目头部 -->
    <view class="question-header">
      <view class="question-type-badge">
        [{{ questionIndex }}/{{ totalQuestions }}: {{ questionTypeText }}]
      </view>
    </view>

    <!-- 题目内容 -->
    <view class="question-content">
      <text class="question-text">{{ questionData.question }}</text>


      <!-- 代码块 -->
      <view class="code-block" v-if="questionData.code">
        <text class="code-text">{{ questionData.code }}</text>
      </view>
    </view>

    <!-- 单选题、判断题选项区域 -->
    <view class="options-area" v-if="questionData.type === '1' || questionData.type === '3'">
      <view class="option-item" v-for="(option, index) in questionData.options" :key="index"
        :class="optionClasses[index]" @click="handleSelectOption(index)">
        <view class="option-label" :class="optionLabelClasses[index]">
          {{ getOptionLabel(index) }}
        </view>
        <text class="option-text">{{ option }}</text>
        <!-- 正确答案标记 -->
        <view class="option-icon correct-icon" v-if="isAnswered && isInCorrectList(index)">✓</view>
        <!-- 用户选择的错误答案标记 -->
        <view class="option-icon error-icon"
          v-else-if="isAnswered && isInSelectedOptions(index) && !questionData.isCorrect">✗</view>
      </view>
    </view>

    <!-- 多选题选项区域 -->
    <view class="options-area" v-if="questionData.type === '2'">
      <view class="option-item" v-for="(option, index) in questionData.options" :key="index"
        :class="optionClasses[index]" @click="handleSelectOption(index)">
        <view class="option-label" :class="optionLabelClasses[index]">
          {{ getOptionLabel(index) }}
        </view>
        <text class="option-text">{{ option }}</text>
        <!-- 正确答案标记 -->
        <view class="option-icon correct-icon" v-if="isAnswered && isInCorrectList(index)">✓</view>
        <!-- 用户选择的错误答案标记 -->
        <view class="option-icon error-icon"
          v-else-if="isAnswered && !questionData.isCorrect && isNotInCorrectList(index)">✗</view>
      </view>
    </view>

    <!-- 多选题确认按钮 -->
    <view class="confirm-answer-btn" v-if="isMultipleChoice && !isAnswered">
      <button class="confirm-btn" @click="handleConfirmAnswer">确认答案</button>
    </view>

    <!-- 单选题，我的答案区域 (答题后显示) -->
    <view class="answer-section" v-if="isAnswered && questionData.type === '1' && !favoriteMode">
      <view class="answer-row">
        <text class="answer-label">我的答案</text>
        <text class="answer-value" :class="isCorrect ? 'correct-text' : 'error-text'">
          {{ getSelectedOptionsText(questionData.correct) }}
        </text>
      </view>
    </view>

    <!-- 判断题，我的答案区域 (答题后显示) -->
    <view class="answer-section" v-if="isAnswered && questionData.type === '3' && !favoriteMode">
      <view class="answer-row">
        <text class="answer-label">我的答案</text>
        <text class="answer-value" :class="isCorrect ? 'correct-text' : 'error-text'">
          {{ getSelectedOptionsText(questionData.correct) }}
        </text>
      </view>
    </view>

    <!-- 多选题，我的答案区域 (答题后显示) -->
    <view class="answer-section" v-if="isAnswered && questionData.type === '2' && !favoriteMode">
      <view class="answer-row">
        <text class="answer-label">我的答案</text>
        <text class="answer-value" :class="isCorrect ? 'correct-text' : 'error-text'">
          {{ getSelectedMultipleOptionsText(questionData.selectedOptionsIndexList) }}
        </text>
      </view>
    </view>

    <!-- 参考答案和解析区域 -->
    <view class="analysis-section" v-if="isAnswered">
      <view class="reference-answer">
        <text class="section-label">参考答案</text>
        <text class="section-content">
          (难度: {{ questionData.difficulty || 4 }}, 易错项: {{ getOptionLabel(questionData.easyWrong ||
            questionData.correct) }})
        </text>
        <view v-if="questionData.type === '1' || questionData.type === '3'" class="correct-answer-box">
          <text class="correct-answer-text">{{ getSelectedOptionsText(questionData.correct) }}</text>
        </view>
        <view v-if="questionData.type === '2'" class="correct-answer-box">
          <text class="correct-answer-text">{{ getSelectedMultipleOptionsText(questionData.correctIndexList) }}</text>
        </view>
      </view>

      <view class="answer-analysis" v-if="questionData.explanation">
        <text class="section-label">答案解析</text>
        <text class="analysis-text">{{ questionData.explanation }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'QuestionCard',
  props: {
    // 题目数据
    questionData: {
      type: Object,
      required: true,
      default: () => ({
        id: '',
        type: 'single', // single: 单选, multiple: 多选, judge: 判断
        difficulty: 'medium', // easy, medium, hard 或 1-5 数字
        question: '',
        code: null,
        options: [],
        correct: 0, // 正确答案的索引
        easyWrong: null, // 易错项索引
        explanation: ''
      })
    },
    // 当前题目索引
    questionIndex: {
      type: Number,
      default: 1
    },
    // 总题目数
    totalQuestions: {
      type: Number,
      default: 1
    },
    // 是否显示难度
    showDifficulty: {
      type: Boolean,
      default: true
    },
    // 是否已经答题(外部控制)
    answered: {
      type: Boolean,
      default: false
    },
    // 外部传入的选中答案
    answer: {
      type: Number,
      default: null
    },
    favoriteMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      selectedOption: null, // 用户选择的选项索引
      _isAnswered: false // 是否已答题（本地状态）
    }
  },
  computed: {
    // 题目类型文本
    questionTypeText() {
      const typeMap = {
        '1': '单选',
        '2': '多选',
        '3': '判断题',
      }
      return typeMap[this.questionData.type] || '单选'
    },
    // 是否为多选题
    isMultipleChoice() {
      return this.questionData.type === '2' || this.questionData.type === 2
    },
    // 是否已答题（优先使用后端数据，否则使用本地状态）
    isAnswered() {
      return this.questionData.hasAnswered !== undefined ? this.questionData.hasAnswered : this._isAnswered
    },
    // 是否答对（优先使用后端数据，否则使用本地计算）
    isCorrect() {
      if (this.questionData.isCorrect !== undefined) {
        return this.questionData.isCorrect
      }
      return this.selectedOption === this.questionData.correct
    },
    // 选项样式类计算属性
    // 选中/取消选择时候的样式改变
    optionClasses() {
      const classes = {}
      if (this.questionData.options && this.questionData.options.length > 0) {
        this.questionData.options.forEach((option, index) => {
          classes[index] = this.getOptionClass(index)
        })
      }
      return classes
    },
    // 选项标签样式类计算属性
    optionLabelClasses() {
      const classes = {}
      if (this.questionData.options && this.questionData.options.length > 0) {
        this.questionData.options.forEach((option, index) => {
          classes[index] = this.getOptionLabelClass(index)
        })
      }
      return classes
    }
  },
  watch: {
    // 监听外部传入的答案
    answer: {
      handler(newVal) {
        if (newVal !== null) {
          this.selectedOption = newVal
        }
      },
      immediate: true
    },
    // 监听外部控制的答题状态
    answered: {
      handler(newVal) {
        this._isAnswered = newVal
      },
      immediate: true
    },
    // 监听题目变化,重置状态
    'questionData.id': {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.resetState()
        }
      }
    },
    // 监听题目数据变化，初始化用户选择
    'questionData.selectedOptions': {
      handler(newVal) {
        if (newVal !== null && newVal !== undefined) {
          if (typeof newVal === 'string') {
            if (this.questionData.type === '2') {
              //把this.questionData.selectedOptions: "A,C",转为['A','C']，再根据correctIndexList，生成selectedOptionsIndexList
              const selectedOptions = newVal.split(',')
              const selectedOptionsIndex = selectedOptions.map(option => this.getOptionIndexFromLabel(option))
              const selectedOptionsIndexList = selectedOptionsIndex.map(option => this.questionData.correctIndexList.findIndex(index => index === option))
              this.questionData.selectedOptionsIndexList = selectedOptionsIndexList
            } else {
              // 如果是字符串格式（如 "A", "B", "C", "D"），转换为索引
              this.selectedOption = this.getOptionIndexFromLabel(newVal)
            }
          } else if (Array.isArray(newVal)) {
            // 如果是数组，取第一个元素
            this.selectedOption = newVal[0]
          } else {
            // 如果是数字索引，直接使用
            this.selectedOption = newVal
          }
        } else {
          // 如果没有选择数据，重置为null
          this.selectedOption = null
        }
      },
      immediate: true
    }
  },
  methods: {
    // 获取选项标签 (A, B, C, D, E...)
    getOptionLabel(index) {
      if (index === null || index === undefined) return ''
      return String.fromCharCode(65 + index)
    },
    // 获取单选题选中选项的文本显示
    getSelectedOptionsText(selected) {
      if (selected === null || selected === undefined) return ''
      if (Array.isArray(selected)) {
        return selected.map(idx => this.getOptionLabel(idx)).join(', ')
      }
      return this.getOptionLabel(selected)
    },
    // 获取多选题选中选项的文本显示
    getSelectedMultipleOptionsText(optionIndexList) {
      if (optionIndexList) {
        const selectedOptions = optionIndexList.map(idx => this.getOptionLabel(idx))
        //把答案按照abcde的顺序进行排列
        selectedOptions.sort((a, b) => {
          const aIndex = a.charCodeAt(0) - 65
          const bIndex = b.charCodeAt(0) - 65
          return aIndex - bIndex
        })
        return selectedOptions.join(', ')
      }
    },
    // 检查索引是否在正确答案列表中
    isInCorrectList(index) {
      const correctIndexList = this.questionData.correctIndexList
      if (!correctIndexList || !Array.isArray(correctIndexList)) return false
      return correctIndexList.includes(index)
    },
    // 检查索引是否在用户选择的选项中
    isInSelectedOptions(index) {
      if (this.selectedOption === null || this.selectedOption === undefined) return false
      if (Array.isArray(this.selectedOption)) {
        return this.selectedOption.includes(index)
      }
      return this.selectedOption === index
    },
    isNotInCorrectList(index) {
      const correctIndexList = this.questionData.correctIndexList
      if (!correctIndexList || !Array.isArray(correctIndexList)) return false
      return !correctIndexList.includes(index)
    },
    // 将选项标签转换为索引 (A->0, B->1, C->2, D->3...)
    getOptionIndexFromLabel(label) {
      if (!label || typeof label !== 'string') return null
      const charCode = label.charCodeAt(0)
      const index = charCode - 65 // A的ASCII码是65
      return index >= 0 ? index : null
    },
    // 处理选项点击
    handleSelectOption(index) {
      // 如果已经答题,不允许再次选择
      if (this.isAnswered) {
        return
      }
      // 如果是多选题，支持多选
      if (this.isMultipleChoice) {
        // 多选题逻辑：切换选中状态
        if (!this.selectedOption) {
          this.selectedOption = []
        }
        const optionIndex = this.selectedOption.indexOf(index)
        if (optionIndex > -1) {
          // 已选中，取消选中
          this.selectedOption.splice(optionIndex, 1)
        } else {
          // 未选中，添加选中
          this.selectedOption.push(index)
        }
        // 单选逻辑：直接设置并标记为已答题
      } else {
        this.selectedOption = index
        this._isAnswered = true
        this.questionData.hasAnswered = true
        if (index === this.questionData.correct) {
          this.questionData.isCorrect = true
        } else {
          this.questionData.isCorrect = false
        }
        this.questionData.selectedOptions = this.getOptionLabel(index)
        // 触发选择事件
        this.$emit('select', {
          selectedOption: index,
          isCorrect: this.isCorrect,
          questionId: this.questionData.id
        })
      }
    },
    // 处理确认答案（多选题）
    handleConfirmAnswer() {
      if (this.isMultipleChoice && this.selectedOption && this.selectedOption.length > 0) {
        this._isAnswered = true
        this.questionData.hasAnswered = true
        // 判断是否答对（需要比对正确答案）
        // 这里假设 correctIndexList 是正确答案的索引数组
        const correctIndexList = this.questionData.correctIndexList
        // 检查所选答案与正确答案是否完全一致
        const isCorrect = correctIndexList.every(index => this.selectedOption.includes(index))

        this.questionData.isCorrect = isCorrect
        this.questionData.selectedOptions = this.selectedOption.map(idx => this.getOptionLabel(idx)).join(',')
        this.questionData.selectedOptionsIndexList = this.selectedOption
        // 触发确认事件给父组件
        this.$emit('multipleChoiceConfirm', {
          selectedOptions: this.selectedOption,
          isCorrect: isCorrect,
          questionId: this.questionData.id
        })
      }
    },
    // 比较两个数组是否相等
    arraysEqual(arr1, arr2) {
      if (arr1.length !== arr2.length) return false
      return arr1.every((val, idx) => val === arr2[idx])
    },
    // 获取选项样式类
    getOptionClass(index) {
      const classes = []
      // 如果已答题，显示答题结果样式
      if (this.isAnswered) {
        // 正确答案样式
        const correctAnswers = Array.isArray(this.questionData.correct)
          ? this.questionData.correct
          : [this.questionData.correct]
        if (correctAnswers.includes(index)) {
          classes.push('correct')
        }
        // 用户选择的答案样式
        const isSelected = Array.isArray(this.selectedOption)
          ? this.selectedOption.includes(index)
          : this.selectedOption === index

        if (isSelected) {
          if (this.questionData.type !== '2') {
            if (this.questionData.isCorrect) {
              // 如果答对了，用户选择的答案也是正确答案
              // classes.push('correct')
            } else {
              // 如果答错了，用户选择的答案显示为错误
              classes.push('incorrect')
            }
          }
        }
      } else {
        // 未答题时，只显示选中状态
        const isSelected = Array.isArray(this.selectedOption)
          ? this.selectedOption.includes(index)
          : this.selectedOption === index
        if (isSelected) {
          classes.push('selected')
        }
      }

      return classes.join(' ')
    },
    // 获取选项标签样式类
    getOptionLabelClass(index) {
      const classes = []
      if (this.isAnswered) {
        if (this.questionData.type === '2') {
          //判断当前index在questionData.correctIndexList中是否存在
          const correctAnswers = this.questionData.correctIndexList.includes(index)
          if (correctAnswers) {
            classes.push('correct-label')
          } else {
            if (!this.questionData.isCorrect) {
              classes.push('incorrect-label')
            }
          }
        } else {
          // 正确答案标签样式
          const correctAnswers = Array.isArray(this.questionData.correct)
            ? this.questionData.correct
            : [this.questionData.correct]
          if (correctAnswers.includes(index)) {
            classes.push('correct-label')
          }
          // 用户选择的答案标签样式
          const isSelected = Array.isArray(this.selectedOption)
            ? this.selectedOption.includes(index)
            : this.selectedOption === index

          if (isSelected) {
            if (this.questionData.isCorrect) {
              // 如果答对了，用户选择的答案标签也是正确样式
              // classes.push('correct-label')
            } else {
              // 如果答错了，用户选择的答案标签显示为错误样式
              classes.push('incorrect-label')
            }
          }
        }
      }
      return classes.join(' ')
    },
    // 重置状态
    resetState() {
      this.selectedOption = null
      this._isAnswered = false
    },
    // 手动设置答题状态(供外部调用)
    setAnswer(index, isAnswered = true) {
      this.selectedOption = index
      this._isAnswered = isAnswered
    }
  }
}
</script>

<style lang="scss" scoped>
.question-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.question-type-badge {
  font-size: 32rpx;
  font-weight: bold;
}

.question-difficulty {
  padding: 6rpx 16rpx;
  border-radius: 15rpx;
  font-size: 26rpx;
  color: #fff;
}

.difficulty-easy,
.difficulty-1,
.difficulty-2 {
  background: #52c41a;
}

.difficulty-medium,
.difficulty-3,
.difficulty-4 {
  background: #1890ff;
}

.difficulty-hard,
.difficulty-5 {
  background: #f5222d;
}

.question-content {
  margin-bottom: 30rpx;
}

.question-text {
  font-size: 32rpx;
  color: #333;
  line-height: 1.8;
  display: block;
}

.code-block {
  background: #f6f8fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-top: 20rpx;
  border-left: 4rpx solid #667eea;
}

.code-text {
  font-family: 'Monaco', 'Consolas', monospace;
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  display: block;
}

.options-area {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
  margin-bottom: 30rpx;
}

.confirm-answer-btn {
  margin-bottom: 30rpx;
}

.confirm-btn {
  width: 100%;
  height: 88rpx;
  background: #5BA2F9;
  color: #fff;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.confirm-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.option-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 25rpx 20rpx;
  display: flex;
  align-items: center;
  border: 2rpx solid #e8e8e8;
  transition: all 0.2s ease;
  position: relative;
  min-height: 90rpx;
}

.option-item.selected {
  border-color: #5BA2F9;
  background: rgba(91, 162, 249, 0.05);
}

.option-item.correct {
  border-color: #52c41a;
  background: rgba(82, 196, 26, 0.1);
}

.option-item.incorrect {
  border-color: #EA5D33;
  background: rgba(234, 93, 51, 0.1);
}

.option-label {
  width: 56rpx;
  height: 56rpx;
  background: #f5f5f5;
  color: #666;
  border-radius: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.option-item.selected .option-label {
  background: #5BA2F9;
  color: #fff;
}

.option-label.correct-label {
  background: #52c41a !important;
  color: #fff !important;
}

.option-label.incorrect-label {
  background: #EA5D33 !important;
  color: #fff !important;
}

.option-text {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  line-height: 1.6;
  padding-right: 40rpx;
}

.option-icon {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 40rpx;
  font-weight: bold;
}

.correct-icon {
  color: #52c41a;
}

.error-icon {
  color: #EA5D33;
}

.answer-section {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
  margin-bottom: 20rpx;
}

.answer-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.answer-label {
  font-size: 30rpx;
  color: #1890ff;
  font-weight: bold;
}

.answer-value {
  font-size: 30rpx;
  font-weight: bold;
}

.correct-text {
  color: #52c41a;
}

.error-text {
  color: #EA5D33;
}

.analysis-section {
  border-top: 1rpx solid #f0f0f0;
  padding-top: 20rpx;
}

.reference-answer {
  margin-bottom: 20rpx;
}

.section-label {
  font-size: 30rpx;
  color: #1890ff;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.section-content {
  font-size: 26rpx;
  color: #999;
  display: block;
  margin-bottom: 15rpx;
}

.correct-answer-box {
  background: #f6f8fa;
  border-radius: 8rpx;
  padding: 15rpx 20rpx;
  display: inline-block;
}

.correct-answer-text {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.answer-analysis {
  margin-top: 20rpx;
}

.analysis-text {
  font-size: 30rpx;
  color: #666;
  line-height: 1.8;
  display: block;
  margin-top: 10rpx;
}
</style>
